# 异步爬取壁纸

import asyncio
import aiohttp

urls = [
    "http://kr.shanghai-jiuxin.com/file/bizhi/20220928/os4harzzjon.jpg",
    "http://kr.shanghai-jiuxin.com/file/bizhi/20220928/qhrbd5foawu.jpg",
    "http://kr.shanghai-jiuxin.com/file/bizhi/20220928/5rwt4wnuguu.jpg"
]

async def aioDownload(url):
    name = url.rsplit("/", 1)[1]
    # 相当于 requests
    # 加了 async 表示异步
    # 加了 with 使用完 session 会自动关闭
    async with aiohttp.ClientSession() as session:
        async with session.get(url=url) as resp:
            with open(name, mode="wb") as f:
                # await 异步写入图片
                f.write(await resp.content.read())
    print(name, " download done")

async def main():
    tasks = []
    for url in urls:
        tasks.append(aioDownload(url))

    await asyncio.wait(tasks)

if __name__ == '__main__':
    asyncio.run(main())
